<template>
	<MainLayout>
		<view class="publish-page u-p-20">
			<!-- 顶部导航栏 -->
			<u-navbar :leftText="'返回'" :leftIcon="'arrow-left'" :title="'编辑信息'" @leftClick="handleBack" fixed
				placeholder />

			<!-- 表单容器 -->
			<u-form :model="form" ref="uForm" :rules="rules" label-width="80">

				<!-- 类型 -->
				<u-form-item label="类型" prop="type">
					<u-radio-group v-model="form.type" placement="row">
						<u-radio v-for="(item, index) in typeList" :key="index" :name="item.value"
							:label="item.label" />
					</u-radio-group>
				</u-form-item>

				<!-- 出发地 -->
				<u-form-item label="出发地" prop="departure">
					<u-input v-model="form.departure" placeholder="请输入出发地" prefixIcon="map" />
				</u-form-item>

				<!-- 目的地 -->
				<u-form-item label="目的地" prop="destination">
					<u-input v-model="form.destination" placeholder="请输入目的地" prefixIcon="map" />
				</u-form-item>

				<!-- 出发时间 -->
				<u-form-item label="出发时间" prop="departureTime">
					<u-input @tap="showDate = true" v-model="form.departureTime" placeholder="请选择出发时间"
						prefixIcon="calendar" readonly />
				</u-form-item>

				<!-- 日期选择器 -->
				<u-datetime-picker v-model="dateValue" :show="showDate" mode="date" @confirm="onDateConfirm"
					@cancel="showDate = false" />

				<!-- 座位/人数 -->
				<u-form-item :label="seatLabel" prop="seats">
					<u-input v-model.number="form.seats" type="number" :placeholder="seatPlaceholder"
						style="width: 100%;" />
				</u-form-item>

				<!-- 备注 -->
				<u-form-item label="备注" prop="remark">
					<view class="textarea-wrapper">
						<u-textarea v-model="form.remark" placeholder="请输入备注" autoHeight :maxlength="maxRemark" />
						<text class="remark-counter" :style="{ color: remainingColor }">
							{{ form.remark.length }}/{{ maxRemark }}
						</text>
					</view>
				</u-form-item>

				<!-- 保存按钮 -->
				<u-form-item>
					<u-button type="primary" shape="circle" @click="submitForm">
						保存
					</u-button>
				</u-form-item>

			</u-form>
		</view>
	</MainLayout>
</template>

<script>
	import api from '@/api'
	import MainLayout from '@/layouts/MainLayout.vue'

	export default {
		components: {
			MainLayout
		},
		data() {
			return {
				journeyId: '',
				form: {
					id: null, // 编辑记录的 id
					type: 'personFindCar',
					departure: '',
					destination: '',
					departureTime: '',
					remark: '',
					seats: null,
				},
				typeList: [{
						label: '人找车',
						value: 'personFindCar',
						seatsLabel: '人数'
					},
					{
						label: '车找人',
						value: 'carFindPerson',
						seatsLabel: '座位'
					}
				],
				showDate: false,
				dateValue: Number(new Date()),
				maxRemark: 15,
				rules: {
					type: [{
						required: true,
						message: '请选择类型',
						trigger: 'blur'
					}],
					departure: [{
						required: true,
						message: '请输入出发地',
						trigger: 'blur'
					}],
					destination: [{
						required: true,
						message: '请输入目的地',
						trigger: 'blur'
					}],
					departureTime: [{
						validator: (rule, value, callback) => {
							if (!value) {
								callback('请选择出发时间')
								return
							}
							const selected = new Date(value)
							const now = new Date()
							if (selected.getTime() <= now.getTime()) {
								callback('出发时间必须大于当前时间')
							} else {
								callback()
							}
						},
						trigger: 'blur'
					}],
					seats: [{
						validator: (rule, value, callback) => {
							const label = this.seatLabel
							if (value === null || value === undefined || isNaN(value)) {
								callback(`请输入${label}`)
							} else if (value <= 0) {
								callback(`${label}必须大于0`)
							} else {
								callback()
							}
						},
						trigger: 'blur'
					}],
					remark: [{
						max: 15,
						message: '备注最多15个字',
						trigger: 'blur'
					}]
				},
			}
		},
		computed: {
			seatLabel() {
				return this.form.type === 'personFindCar' ? '人数' : '座位'
			},
			seatPlaceholder() {
				return this.form.type === 'personFindCar' ?
					'请输入需要乘坐的人数' :
					'请输入可乘坐的人数'
			},
			remainingColor() {
				const remain = this.maxRemark - this.form.remark.length
				if (remain <= 0) return 'red'
				if (remain <= this.maxRemark * 0.3) return 'orange'
				return '#999'
			}
		},
		watch: {
			'form.type'() {
				if (this.$refs.uForm) {
					this.$nextTick(() => {
						this.$refs.uForm.validateField('seats')
					})
				}
			}
		},
		onLoad(options) {
			// onLoad 最早执行，这里拿到参数
			this.journeyId = options.journeyId
		},
		mounted() {
			this.loadDetail()
		},

		methods: {
			async loadDetail() {
				try {
					const res = await api.journey.detail({
						id: this.journeyId
					}) // 获取传入的 id

					if (res.code === 200 && res.data) {
						this.form.id = res.data.id
						this.form.type = res.data.type
						this.form.departure = res.data.departure
						this.form.destination = res.data.destination
						this.form.departureTime = res.data.departure_time.slice(0, 10)
						this.form.remark = res.data.remark
						this.form.seats = res.data.seats
						this.dateValue = new Date(this.form.departureTime).getTime()
					}
				} catch (err) {
					console.error('获取详情失败:', err)
					uni.showToast({
						title: '获取详情失败',
						icon: 'error'
					})
				}
			},
			onDateConfirm(e) {
				const date = new Date(e.value)
				const y = date.getFullYear()
				const m = String(date.getMonth() + 1).padStart(2, '0')
				const d = String(date.getDate()).padStart(2, '0')
				this.form.departureTime = `${y}-${m}-${d}`
				this.showDate = false
			},
			async submitForm() {
				try {
					await this.$refs.uForm.validate()
					const res = await api.journey.edit(this.form) // 调用编辑接口
					if (res.code === 200) {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
						setTimeout(() => uni.redirectTo({
							url: '/pages/mine/myTrip'
						}), 1500)
					} else {
						uni.showToast({
							title: res.msg || '保存失败',
							icon: 'none'
						})
					}
				} catch (err) {
					if (err && err.length) {
						uni.showToast({
							title: err[0].message,
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: '表单校验失败',
							icon: 'none'
						})
					}
				}
			},
			handleBack() {
				uni.redirectTo({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style scoped>
	.publish-page {
		background-color: #fff;
		margin: 30rpx;
	}

	.textarea-wrapper {
		position: relative;
		width: 100%;
	}

	.remark-counter {
		position: absolute;
		right: 10rpx;
		bottom: 10rpx;
		font-size: 24rpx;
		pointer-events: none;
	}
</style>